(function(namespace) {

    window.VK_LEFT = window.VK_LEFT || 37;
    window.VK_RIGHT = window.VK_RIGHT || 39;
    window.VK_UP = window.VK_UP || 38;
    window.VK_DOWN = window.VK_DOWN || 40;
    window.VK_ENTER = window.VK_ENTER || 13;
    window.VK_BACK = window.VK_BACK || 46;
    window.VK_BACK_SPACE = window.VK_BACK_SPACE || 46;
    window.VK_EXIT = window.VK_EXIT || 45;
    window.VK_ESC = window.VK_ESC || 27 || 8;   //paa paticom for morefun

    window.VK_PLAY = window.VK_PLAY || 191;             // / 
    window.VK_PAUSE = window.VK_PAUSE || 190;           // .
    window.VK_STOP = window.VK_STOP || 83;              // s
    window.VK_TRACK_NEXT = window.VK_TRACK_NEXT || 78;  // n
    window.VK_TRACK_PREV = window.VK_TRACK_PREV || 80;  // p
    window.VK_FAST_FWD = window.VK_FAST_FWD || 70;      // f
    window.VK_REWIND = window.VK_REWIND || 82;          // r
    
    namespace.MI = {}, namespace.UI = {};
    UI.getX = 
    function (a){return a.getBoundingClientRect?a.getBoundingClientRect().left+UI.scrollX():(a.offsetParent?a.offsetLeft+UI.getX(a.offsetParent):a.offsetLeft)+("fixed"==UI.C(a,"position")?UI.scrollX():0)}
    UI.scrollX = 
    function (a){var b=document.documentElement;if(a){var c=a.parentNode,f=a.scrollLeft||0;a==b&&(f=UI.scrollX());return c?f+UI.scrollX(c):f}return self.pageXOffset||b&&b.scrollLeft||document.body.scrollLeft}
    UI.scrollY = 
    function (a){var b=document.documentElement;if(a){var c=a.parentNode,f=a.scrollTop||0;a==b&&(f=UI.scrollY());return c?f+UI.scrollY(c):f}return self.pageYOffset||b&&b.scrollTop||document.body.scrollTop}
    UI.getY = 
    function (a){return a.getBoundingClientRect?a.getBoundingClientRect().top+UI.scrollY():(a.offsetParent?a.offsetTop+UI.getY(a.offsetParent):a.offsetTop)+("fixed"==UI.C(a,"position")?UI.scrollY():0)} 
    UI.scrollTo = 
    function (a,b,c){if(a==document.documentElement||a==document.body)return window.scrollTo(b,c)} 

    MI.string = {
    cut: function (a,b,c){var c=UI.isUndefined(c)?"...":c,e=[],f="";if(MI.string.length(a)>b){a=a.split("");UI.each(a,function(a){if(b>0){e.push(a);b=b-MI.string.length(a)}else return 1});f=e.join("")+c}else f=a;return f}
    ,entityReplace: function (a){return String(a).replace(/&#38;?/g,"&amp;").replace(/&amp;/g,"&").replace(/&#(\d+);?/g,function(a,b){return String.fromCharCode(b)}).replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&nbsp;/g," ").replace(/&#13;/g,"\n").replace(/(&#10;)|(&#x\w*;)/g,"").replace(/&amp;/g,"&")}
    ,escape: function (a){return MI.string.html(a).replace(/'/g,"\\'")}
    ,escapeReg: function (a){var a=String(a);for(var b=[],c=0;c<a.length;c++){var e=a.charAt(c);switch(e){case ".":case "$":case "^":case "{":case "[":case "(":case "|":case ")":case "*":case "+":case "?":case "\\":b.push("\\x"+e.charCodeAt(0).toString(16).toUpperCase());break;default:b.push(e)}}return b.join("")}
    ,html: function (a){var a=String(a).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),b=a.replace(/\/\*(\s|.)*?\*\//g,"");b.match(/expression/g)&&(a=b.replace(/expression/g,"expressio n"));return a}
    ,length: function (a){var b=String(a||"").match(/[^\x00-\x80]/g);return a.length+(b?b.length:0)}
    ,sprintf: function (){var a=arguments,b=a[0]||"",c,e;c=1;for(e=a.length;c<e;c++)b=b.replace(/%s/,a[c]);return b}
    ,trim: function (a){return String(a).replace(/(^\s*)|(\s*$)/g,"")}
    ,checkURL: function (a){var r = new RegExp('((news|telnet|nttp|file|http|ftp|https)://){1}(([-A-Za-z0-9]+(\\.[-A-Za-z0-9]+)*(\\.[-A-Za-z]{2,5}))|([0-9]{1,3}(\\.[0-9]{1,3}){3}))(:[0-9]*)?(/[-A-Za-z0-9_\\$\\.\\+\\!\\*\\(\\),;:@&=\\?/~\\#\\%]*)*','i'); return r.test(a)}
    }
    
}(window));


(function(namespace) {
    function xhr(){ }
    namespace.xhr = xhr;
    xhr.path =  '/DslAjaxJsbridgeServletV2';
	//ati qb2  '/vdx/api_dsl.jsp';

    xhr.abort = function(req_id){
        var abt = function(i){
            var req = xhr.abort[i];
            req && req.abort && req.abort();
            req = null;
            delete xhr.abort[i];
        };
        if (req_id == null) {
            for (var i in xhr.abort){
                abt(i)
            }
        }else{
            abt(req_id)
        }
    };
    xhr.req = function(data, fn, err){
        xhr.abort();

        var req_id = (new Date()).getTime();
        xhr.abort[req_id] = 
        $.ajax({
          type: 'get',
          url: xhr.path,
          // data to be added to query string:
          data: data,//{ name: 'Zepto.js' },
          // type of data we are expecting in return:
        //  dataType: 'json',
          //timeout: 300,
          //context: $('body'),
          success: function(d){
            // Supposing this JSON payload was received:
            //   {"project": {"id": 42, "html": "<div>..." }}
            // append the HTML to context object.
            //this.append(data.project.html)
            //console.log(2222, d, fn);
            fn && fn(d);
            xhr.abort(req_id);
          },
          error: function(x, type){
            console && console.log && console.log('xhr Error');
			console.log("x:"+x+",type:"+type);
            err && err(x, type);
          }
        });

        return req_id;
    };

     xhr.get_hot = function(fn, err){
        xhr.req({http_param: 'select   * from gv_material '}, fn, err);
    };

    xhr.get_category = function(fn, err){
        xhr.req({http_param: 'select  * from gv_material'}, fn, err);
    };
//depre qb2
    xhr.get_filter_by = function(f, value, fn, err){
        var sql_t;
		//ati p89  search by cate
        if (f == 'filter_by_cate'){
			threadLocalParamMap={};
            
			threadLocalParamMap.fn=fn;
			threadLocalParamMap.err=err;
			threadLocalParamMap.xhr=xhr;
			threadLocalParamMap.value=value;
			//alert("get_posts_befor");
			get_posts(threadLocalParamMap);
		  
        }else if (f == 'filter_by_region'){
            sql_t = 'area';
            xhr.req({http_param: 'select   * from gv_material where '+[sql_t, '=', value].join(' ')}, fn, err);
        }else if (f == 'filter_by_date'){
            sql_t = 'year';
            var symbol = '=';
            if (value = 'EARLY'){
                symbol = '<', value = '2006';
            }
            xhr.req({http_param: 'select   * from gv_material where '+[sql_t, symbol, value].join(' ')}, fn, err);
        }else if (f == 'filter_by_hot'){
            xhr.req({http_param: 'select  * from gv_material order by '+value}, fn, err);
        }
    };

    xhr.get_recommend = function(spid, fn, err){
        xhr.req({http_param: 'select  * from gv_material where special_id='+spid+' '}, fn, err);
    };

    xhr.get_movie_detail = function(mid, fn, err){
		
		threadLocalParamMap={};            
			threadLocalParamMap.fn=fn;  //set callback detail_intro
			threadLocalParamMap.err=err;
			threadLocalParamMap.xhr=xhr;
		//	threadLocalParamMap.value=value;
			get_post(mid);
     
    };
   //movie_page
    xhr.search_keyword = function(keyword, fn, err){
		
		
       
    };
    
    function render(){ }
    namespace.render = render;

    render.repaint_movie_page = function(){
        var s, rect = {}, window_rect = 
            {left:-$(window).width(), top:0, right:$(window).width()*2, bottom:$(window).height() }
        ;
        $('.activeview .movie_page .item img.img_item').each(function(){
            rect = get_rect(this);
            s = intersect_rect(rect, window_rect);
            if (s){
                $(this).attr('src', $(this).attr('_src'))
            }
        });
    };

    render.set_movie_list_auto = function(){
        var outter_w = 0;
        $('.activeview .movie_list .movie_page').each(function(){
            outter_w += $(this).width();
        });
        $('.activeview .movie_list').width(outter_w);
        render.repaint_movie_page();
    };
	
	//ati pb28 search after list evenet 
    render.movie_list = function(data, style, err_txt){
        data = data || {};
        var rows = data.rows, r, o = [];
        for (var i=0,j=rows.length; i<j; i++){
					r = rows[i];
					//paa
					var img_src=$approot+"/" +r.thumb;
				if(	inDesktopMode())
				{
					img_src= "file:///"+r.thumb;
				}
				//paa end
					var html_str='<a class="item mvitem ' +(style||'mv')+ '" href="javascript:void(0)" e="mv_detail" page_hint="'+(i+1)+'/'+j+'" mid="' +r.material_id+ '"><img class="img_item" _src="' +img_src+ '"><h3 class="b c"><span>' +r.material_description+ '</span></h3></a>';
				//	alert(r.material_id);
					o.push(html_str);
        }
        var w = Math.max(((style=='mv_tiny')?310:390) * o.length, 1000);
        if (o.length <= 0) o.push('<h2>' +(err_txt||'没有找到相关影片，请更换其他搜索条件。')+ '</h2>');

        o.unshift('<div class="page_hint">'+1+'/'+rows.length+'</div><div class="movie_page clearfix qc9 mvsQc9" style="width:' +w+ 'px">');
        o.push('</div>')
        $('.activeview .movie_list').append(o.join(''));
        render.set_movie_list_auto();
		
		
		/*
		bindClsEvt("mvitem_right",function(){
				var now_elem=get_curr_hover();
				var li=$(".mvitem");//length
				for(var i=0;i<li.length;i++)
				{
					var item=li[i];
					if($(item).hasClass("hover"))
					{
						$(item).removeClass("hover");
						var nextQc9=$(li[i+1]);
						nextQc9.addClass("hover");
						break;
					}
				}
		//	if( $(now_elem).hasClass("cateitem") )
		//	$("#menu2").addClass("enterCateItem");
			
			} );
			*/
    };
	
	
//qb2  cate filt callback
    render.movie_list_normal = function(data, err_txt){
        $('.activeview .movie_list').html('');
        $('.activeview .movie_list').css('marginLeft',0);
        render.movie_list(data, null, err_txt);
    };
	//qb2 for search callback
    render.movie_list_tiny = function(data, err_txt){
        $('.activeview .movie_list').html('');
        $('.activeview .movie_list').css('marginLeft',0);
        render.movie_list(data, 'mv_tiny', err_txt);
    };
    
    function key_events(){ }
    namespace.key_events = key_events;

//ati p6a add recomm  and enterKey eventCallback
//ati qb2  curr is cate pic when cate pic click
     key_events.enter = function(curr){
        curr = curr || $(get_curr_hover());
        
        if (curr.hasClass('nav_tab')){
            curr.parent().find('a').removeClass('selected');
            curr.addClass('selected');
            
        //     $('.activeview .movie_list').html($('script[name="' +curr.attr('e')+ '"]').text());
        }
        var e = curr.attr('e');
        if (e){
            // get history
            key_events.backlast.data.push($('.activeview').html());
            key_events[e] && key_events[e](e, curr);
        }
    };

    key_events.key = function(e, curr){
        var value = curr.html();
        $('.searchbox .textbox').append(value);
    };
    key_events.key_space = function(e, curr){
        $('.searchbox .textbox').append(' ');
    };
    key_events.key_backspace = function(e, curr){
        var value = $('.searchbox .textbox').text();
        $('.searchbox .textbox').html(value.substr(0, value.length-1));
    };
	//ati add recomm pb28   key_search_clickOrEnter
    key_events.key_search = function(e, curr){

		try{
			start_load_lyofe();  //for load ui effek
			var keyword = $('.searchbox .textbox').text();
			
			//search_keyword===	query_posts(keyword);
			
			
			var search_callback= function(data){
				render.movie_list_tiny(data);
				
				//ati p89
			//	$(".searchbox").hide();
				search_finish();
      	     };
			 
			threadLocalParamMap={};            
			threadLocalParamMap.fn=search_callback;
		//	threadLocalParamMap.err=err;
			threadLocalParamMap.xhr=xhr;
			//threadLocalParamMap.value=value;
			query_posts(keyword);
		//	xhr.search_keyword(value,search_callback);
		}catch(e)
		{
			showErr(e);
		}
    };
   //qb2 ati
      function key_search_evt   (e, curr){

		try{
			start_load_lyofe();  //for load ui effek
			var value = $('.searchbox .textbox').text();
			
			//search_keyword===	query_posts(keyword);
			xhr.search_keyword(value, function(data){
				render.movie_list_tiny(data);
				
				//ati p89
			//	$(".searchbox").hide();
				search_finish();
      	  });
		}catch(e)
		{
			showErr(e);
		}
     }
    //qbf ori is .text(),arg html();
    key_events.get_tmpl = function(e){ return $('noscript[name="' +e+ '"]').text() };
    

  key_events.backlast = function(e, curr){
        //key_events.backlast.data.pop();
        if (key_events.backlast.data.length > 1){
            var last = key_events.backlast.data.pop();
            $('.activeview').html(last);//key_events.backlast.data[key_events.backlast.data.length-1])
        }else{
            key_events.backhome();
        }
    };
    key_events.backlast.data = [];

    key_events.mv_list = 
    key_events.mv_hot = 
    key_events.backhome = function(e, curr){
        $('.activeview .nav').html(key_events.get_tmpl('nav_home'));
        $('.activeview .movie_list').css('marginLeft',0);
		 var mv_hot_html=key_events.get_tmpl('mv_hot');
		//mv_hot_div=$(
	// alert(mv_hot_html);
      $('.activeview .movie_list').html(mv_hot_html);
	 //    $("#mv_hot_div").show();
		// alert($("#first_movie").prop('outerHTML'));
		 window.setTimeout(function(){
			//  alert($("#first_movie").prop('outerHTML'));
		 },100);
		 //prop('outerHTML')
         $('.activeview .searchbox').html(key_events.get_tmpl('mv_searchbox'));
        $('body').css({'background-image':'url(images/bg.jpg)'});
          render.set_movie_list_auto();
	 //	alert($("#first_movie").prop('outerHTML'));
        /*
        xhr.abort();
        xhr.get_hot(function(data){
            data = data || {};
            var rows = data.rows, r, o = [];
            for (var i=0,j=rows.length; i<j; i++){
                r = rows[i];
                $('.activeview .movie_list .item').eq(i).attr({
                    e:'mv_detail',
                    mid:r.material_id
                })
                $('.activeview .movie_list .item img').eq(i).attr('src', '/vdx/' +r.thumb)
                $('.activeview .movie_list .item h3 span').eq(i).text(r.material_description);
                
                //o.push('<a class="item ' +(style||'mv')+ '" href="javascript:void(0)" e="mv_detail" mid="' +r.material_id+ '"><img src="/vdx/' +r.thumb+ '"><h3 class="b c"><span>' +r.material_description+ '</span></h3></a>');
            }
        });
*/
    };

    // key_events.mv_list = 
    // key_events.mv_hot = function(e, curr){
    //     $('.activeview .nav').html(key_events.get_tmpl('nav_home'));
    //     $('.activeview .movie_list').css('marginLeft',0)
    //     $('.activeview .movie_list').html(key_events.get_tmpl(e));
    //     $('.activeview .searchbox').html(key_events.get_tmpl('mv_searchbox'));
    //     render.set_movie_list_auto();
    // };
    key_events.mv_cate = function(e, curr){
        $('.activeview .nav').html(key_events.get_tmpl('nav_cate'));
        $('.activeview .movie_list').css('marginLeft',0);
        $('.activeview .movie_list').html(key_events.get_tmpl(e));
        $('.activeview .searchbox').html(key_events.get_tmpl('mv_searchbox'));
        $('body').css({'background-image':'url(images/bg.jpg)'});
        render.set_movie_list_auto();
        xhr.abort();
    };
    key_events.mv_recomm = function(e, curr){
        $('.activeview .nav').html(key_events.get_tmpl('nav_recomm'));
        $('.activeview .movie_list').css('marginLeft',0);
        $('.activeview .movie_list').html(key_events.get_tmpl(e));
        $('.activeview .searchbox').html(key_events.get_tmpl('mv_searchbox'));
        $('body').css({'background-image':'url(images/bg.jpg)'});
        render.set_movie_list_auto();
        xhr.abort();
    };
    key_events.mv_my = function(e, curr){
        $('.activeview .nav').html(key_events.get_tmpl('nav_my'));
        $('.activeview .movie_list').css('marginLeft',0)
        $('.activeview .movie_list').html(key_events.get_tmpl(e));
        $('.activeview .searchbox').html(key_events.get_tmpl('mv_searchbox'));
        $('body').css({'background-image':'url(images/bg.jpg)'});
        render.set_movie_list_auto();
        xhr.abort();
    };

    key_events.mv_search = function(e, curr){
        $('.activeview .nav').html(key_events.get_tmpl('nav_search'));
        $('.activeview .movie_list').css('marginLeft',0)
        $('.activeview .movie_list').html(key_events.get_tmpl(e));
        $('.activeview .searchbox').html(key_events.get_tmpl('mv_keypad'));
        $('body').css({'background-image':'url(images/bg.jpg)'});
        render.set_movie_list_auto();
        xhr.abort();
    };
    
    key_events.ly_cate = 
    key_events.ly_region = 
    key_events.ly_date = 
    key_events.ly_hot = function(e, curr){
        $('.container').removeClass('activeview');
        $('.layer').addClass('activeview');
        $('.layer').html(key_events.get_tmpl(e));
        $('.activeview a').eq(1).addClass('hover');
    };

    key_events.filter_close_layer = function(e, curr){
        $('.container').addClass('activeview');
        $('.layer').removeClass('activeview');
    };
	
	
	//ati pa2 list_by_cate_finish event
	function load_finish_p89(){
		var first_obj=	$('.activeview .movie_list .movie_page a')[0];
		$(first_obj).addClass("hover");
		
		$(".nav_tab").removeClass("hover");
		// alert("--  load_finish_p89 ");
		//if(console)
		try{
	 console.log(first_obj);
	//	 alert("--  load_finish_p89  a2");
		}catch(e){}
	}
	//ati p89 add .beir  filter_by_cate yash empty
//ati qb2  e = "filter_by_cate", curr = [a.item.h2.hover, selector: "
    key_events.filter_by_cate = function(e, curr){
		//ati p89
		//e8=filter_by_cate
		//curr=a.item.h2 hover
        var value = curr.attr('value') || curr.text();
		var flt_by_cate= function(data){
            render.movie_list_normal(data);
			load_finish_p89();
        };
     //   xhr.get_filter_by(e, value,flt_by_cate);
		
		//ati p89  search by cate
      //  if (f == 'filter_by_cate'){
			threadLocalParamMap={};
            
			threadLocalParamMap.fn=flt_by_cate; //callback
		//	threadLocalParamMap.err=err;
			threadLocalParamMap.xhr=xhr;
			threadLocalParamMap.value=value;
			//alert("get_posts_befor");
			get_posts(threadLocalParamMap);
		//ati p89 show the new bycate saerch mvs div .and hide the last div 
        setTimeout(function(){ key_events.filter_close_layer(); }, 300)
    };
    key_events.filter_by_region = 
    key_events.filter_by_date = 
    key_events.filter_by_hot = function(e, curr){
		//ati p89
		//e8=filter_by_cate
		//curr=a.item.h2 hover
        var value = curr.attr('value') || curr.text();
        xhr.get_filter_by(e, value, function(data){
            render.movie_list_normal(data);
        });
		//ati p89 show the new bycate saerch mvs div .and hide the last div 
        setTimeout(function(){ key_events.filter_close_layer(); }, 300)
    };

    key_events.filter_by_recomm = function(e, curr){
        var value = curr.attr('value') || 1 || 2 || 3;
        xhr.get_recommend(value, function(data){
            render.movie_list_normal(data);
        });
    };
    
    //paa add recomm get_post(
	//pb28 add recomm    detail item clien event  ,,get_movie_detail is invoke my detail_client() ,then callback
    key_events.mv_detail = function(e, curr){
        var mid = curr.attr('mid');
		//alert(" item id:"+mid);
        if (!mid)		
		{
			alert(" no mid!! 不能找到项目id,maybe cant find mv filepath,confirm mv path is exist");
			 return;
		
		}
        $('.activeview .nav').html(key_events.get_tmpl('nav_back'));
        $('.activeview .movie_list').css('marginLeft',0);
        $('.activeview .movie_list').html(key_events.get_tmpl(e));
        $('.activeview .searchbox').html(key_events.get_tmpl('mv_searchbox'));
        $('.activeview .movie_page .btn_play').addClass('hover');
     //   xhr.get_movie_detail(mid, function(data){  //qb2 jeig sh invoke get_post_single,then callback
			
				//qb2   goto cms api.la..		
      //  });   // ati qb2  end get_movie_detail;
		// get_movie_detail function(mid, fn, err)
		
			threadLocalParamMap={};            
		//	threadLocalParamMap.fn=fn;  //set callback detail_intro
		   //threadLocalParamMap.err=err;
			threadLocalParamMap.xhr=xhr;
		//	threadLocalParamMap.value=value;
			get_post(mid);
    };

//paa jeig meth haosyo mayong ,use d sh detail()
//qb2   confirm haosyo not use .. use detail api ..
    key_events.mv_detail3 = function(e, curr){
        var mid = curr.attr('mid');
		//alert("mid pac:"+mid);
        if (!mid) return;
        $('body').css({'background-image':'url(images/bg.jpg)'});
        $('.activeview .movie_list').css('marginLeft',0);
        $('.activeview .movie_list').html(key_events.get_tmpl(e));
        $('.activeview .searchbox').html(key_events.get_tmpl('mv_searchbox'));
        $('.activeview .movie_page .btn_play').addClass('hover');
        xhr.get_movie_detail(mid, function(data){
            data = data || {};
            var rw = data.rows || [],
                r = data.rows[0] || {},
                name = MI.string.html(String(r.material_description)),
                thumb = '/vdx/' +r.thumb,
                file_path = '/vdx/' +r.file_path,
                detail = MI.string.html(String(r.detail));

            $('body').css({'background-image':'url('+thumb+')'});
            $('.activeview .movie_page h2').text(name);
            //$('.activeview .movie_page img').attr('src',thumb);
            $('.activeview .movie_page .movie_detail').html(detail);
		//	alert("v3");
            $('.activeview .movie_page .btn_play').attr('url', file_path);
			//ati p89
			  $('.activeview .movie_page .btn_play').attr('mvid', mid);
        });
    };
    key_events.playmovie = function(e, curr){
		
		try{
        var url = $(curr).attr('url');
        if (typeof playx == 'function' && url){
            $('body').append('<div class="loading">Loading...</div>');
            setTimeout(function(){ $('.loading').remove() }, load_timeout*1000); // remove loading after 6s
			//ati 
			// if (typeof playx_v2 == 'function' )
//			 {
//				 var mov_id=$(curr).attr('id');
				var $mvid= $(curr).attr('mvid');
				playx_v3(url, $mvid);
			// }else
          //  playx(url);  //default
        }
		}catch(e)
		{
		showErr(e);	
		}
    };


    // --------------------------------------------
    // core algorithm for processing
    // --------------------------------------------

    // get a node's bounding rectangle
    function get_rect(node){
        var x, y;
        x = UI.getX(node), y = UI.getY(node),
        o = {
            node: node,
            left: x,
            top: y,
            right: x + $(node).width(),
            bottom: y + $(node).height()
        };
        return o;
    }
    
    // re-calculate all the bounding box on the screen
    function re_calc_bounding(){
        var boundinglist = [];
        $('.activeview a').each(function(){
            boundinglist.push(get_rect(this));
        })
        return boundinglist;
    }
    
    // detect 2 bounding rectangles are intersected
    function intersect_rect(r1, r2) {
        return !(r2.left > r1.right || 
        r2.right < r1.left || 
        r2.top > r1.bottom ||
        r2.bottom < r1.top);
    }
    
    // get current hovered object
    function get_curr_hover(){
        return $('.activeview .hover')[0] || $('.activeview a')[0] || null;
    }
    
    // get a bounding rectangle by direction (vertical or horizontal)
    function get_rect_by_dir(from, direction){
        var o = {}, x, y;
        x = from.left, y = from.top, o = from;
        direction = direction.toUpperCase();
        if (direction == 'LEFT'){
            o.left = 0;
        }else if (direction == 'RIGHT'){
            o.right = $(window).width();
        }else if (direction == 'UP'){
            o.top = 0;
        }else if (direction == 'DOWN'){
            o.bottom = $(window).height();
        }
        return o;
    }

    // get a next object by direction
    function get_next_hover_by_dir(direction){
        if (!direction) return;

        var boundinglist = re_calc_bounding(), intersectedlist = [], n;
        var curr = get_curr_hover(), r_curr, r1, r2, r;
        var w, h, w_offset, h_offset;
        
        for (var i=0,j=boundinglist.length; i<j; i++){
            n = boundinglist[i];
            
            r_curr = get_rect(curr);
            w = r_curr.right - r_curr.left;
            h = r_curr.bottom - r_curr.top;
            w_offset = (w - w/1.3) /2;
            h_offset = (h - h/1.3) /2;
            // for get actual size before scale effect added
            r_curr.top += h_offset;
            r_curr.left += w_offset;
            r_curr.right -= w_offset;
            r_curr.bottom -= h_offset;
            
            r1 = get_rect_by_dir(r_curr, direction);
            r2 = n;
            if (r1.node == r2.node) continue; // is self ?
            //console.log(r1, r2);
            r = intersect_rect(r1, r2);
            
            // get all of the intersected
            if (r){
                intersectedlist.push(r2);
            }
        }
        // sort all of the intersected, and select a nearest one.
        if (intersectedlist.length > 0){
            // get attr by direction
            var attr = {'left':'right', 'right':'left', 'up':'bottom', 'down':'top' }[direction],
                next_hover;

            function show_arr(aa){
                var rr = [];
                for (var ii =0,jj=aa.length;ii<jj;ii++){
                    rr.push(aa[ii]);
                }
                return rr;
            }    
            intersectedlist.sort(function(a, b){
                //console.log(attr, a[attr], b[attr], a[attr] <= b[attr]);
                //console.log(show_arr(intersectedlist));
                return a[attr] < b[attr] ? -1 : a[attr] > b[attr] ? 1 : 0; 
                //return a[attr] <= b[attr];
            });

            $('.activeview a').removeClass('hover');
            // add hover effect as selected
            if (attr == 'left' || attr == 'top') // ie need reverse ?
                next_hover = intersectedlist[0].node//pop().node
            else
                next_hover = intersectedlist[intersectedlist.length-1].node;

            //console.log(333, attr, intersectedlist);
            
            var offset_left = UI.getX(next_hover),
                offset_right = UI.getX(next_hover) + $(next_hover).width(),// - ($(window).width() - 30),
                margin_left = Number(String($(next_hover).parent().parent().css('marginLeft')).replace('px','') || 0),
                move_left = 0;

                if ($(next_hover).hasClass('item')){
                    if (offset_right > $(window).width()){
                        move_left = margin_left-offset_left+$(next_hover).width()+33;
                        console.log(move_left, offset_left, $(window).width(), move_left < $(window).width()-$(next_hover).parent().parent().width());
                        if (move_left < $(window).width()-$(next_hover).parent().parent().width()) move_left = $(window).width()-$(next_hover).parent().parent().width()-33;
                        $(next_hover).parent().parent().css({'marginLeft': move_left});
                    }
                    else if (offset_left < 0){
                        move_left = margin_left+$(window).width()-$(next_hover).width()-66;
                        if (move_left > 0) move_left = 0;
                        $(next_hover).parent().parent().css({'marginLeft': move_left});
                    }
                }

            /*
            if ($(next_hover).hasClass('item') && (offset_right > 0 || offset_left < 0)){
                margin_left = -offset_left + 44;
                if (margin_left > 0) margin_left = 0;
                $(next_hover).parent().parent().css({'marginLeft': margin_left});
            }
            */
            // set next object as hovered
            $(next_hover).addClass('hover');
            return next_hover;
        }
        
    }


    // --------------------------------------------
    // UI interaction
    // --------------------------------------------
    $(document).live('click', function(e){
        console.log(e, e.target);
        key_events.enter($(e.target));
    });
	//ati addd recomm  key evente all..code sh nad .n d only recomm
    $(document).on('keydown', function(e){
        var direction, next_hover;
        //console.log(e.keyCode)
		//paa  add e.keyCode==8 backend
        if (e.keyCode == VK_ESC || e.keyCode == VK_EXIT || e.keyCode==8){
            if ($('.layer').hasClass('activeview')){
                key_events.filter_close_layer();
            }else{
                setTimeout(function(){ key_events.backlast(); }, 100);
            }
            return;
        }else if (e.keyCode == VK_LEFT){
            direction = 'left';
        }else if (e.keyCode == VK_RIGHT){
            direction = 'right';
        }else if (e.keyCode == VK_UP){
            direction = 'up';
        }else if (e.keyCode == VK_DOWN){
            direction = 'down';
		//	alert(direction);
			//ati p89
			//alert("firsst mov has hover "+$("#first_movie").hasClass("hover"));
			if($("#first_movie").hasClass("hover"))
			{
				$("#first_movie").removeClass("hover");
				$(".btn_search").addClass("hover");
				//alert("ok...");
				window.setTimeout(function(){
					$("#first_movie").removeClass("hover");
				$(".btn_search").addClass("hover");
					//alert("set timeout event");
				},500);
			}
        }else if (e.keyCode == VK_ENTER){
            setTimeout(function(){
                key_events.enter();     // press OK
            }, 100);
            //key_events.enter();
			var now_elem=get_curr_hover();
			if( $(now_elem).hasClass("cateitem") )  // if is cateitem
				exeClsEvt("cateitem_enter");
			if( $(now_elem).hasClass("mvitem") )	
					exeClsEvt("mvitem_enter");
            return;
        }
		
			//qc9
		var now_elem=get_curr_hover();
		var now_elem_id=$(now_elem).attr("id");
		if(exeEvt(now_elem_id+"_"+direction))
		{
			return;
		}
		// cls evt dispatcher  fenfacyi..
		var clsQc9=$(now_elem).attr("class");
		var cls_arr=clsQc9.split(" ");
		for(var idx in cls_arr)
		{
			var clsQc8=cls_arr[idx];
			if(clsQc8)
			if(exeClsEvt(clsQc8+"_"+direction))
			{
				return;
			}
			
		}
		
		
		
        if (direction){
			var curr_hover_obj=get_curr_hover();
            var from_is_hv_tab = $(curr_hover_obj).hasClass('hv_tab');
            next_hover = get_next_hover_by_dir(direction);
			
			next_hover=set_next_hover(next_hover,curr_hover_obj,direction);
            
            if ($('.page_hint').length >0 && $(next_hover).attr('page_hint')){
                $('.page_hint').html($(next_hover).attr('page_hint'));
            }
            
            if (next_hover && $(next_hover).hasClass('hv_tab') && from_is_hv_tab){
                setTimeout(function(){
                    key_events.enter();
                }, 300);
            }
            render.repaint_movie_page();
        }
		
	

    });
	
	//ati p89
	function esc_event()
	{
		 if(console)
		console.log("----enter esc event");
		  if ($('.layer').hasClass('activeview')){
                key_events.filter_close_layer();
            }else{
                setTimeout(function(){ key_events.backlast(); }, 100);
            }
		
	}
	
	 $("#retBtnP89").on('click', function(e){
        console.log(e, e.target);
        esc_event(); 
    });
	function key_eventP89(direction)
	{
		  var  next_hover;
		    if (direction){
			var curr_hover_obj=get_curr_hover();
            var from_is_hv_tab = $(curr_hover_obj).hasClass('hv_tab');
            next_hover = get_next_hover_by_dir(direction);
            
            if ($('.page_hint').length >0 && $(next_hover).attr('page_hint')){
                $('.page_hint').html($(next_hover).attr('page_hint'));
            }
            
            if (next_hover && $(next_hover).hasClass('hv_tab') && from_is_hv_tab){
                setTimeout(function(){
                    key_events.enter();
                }, 300);
            }
            render.repaint_movie_page();
        }
		
	}
	 $("#preBtnP89").on('click', function(e){
        console.log(e, e.target);
        key_eventP89("left"); 
    });
	 $("#nextBtnP89").on('click', function(e){
        console.log(e, e.target);
        key_eventP89("right"); 
    });
	
	function search_finish(){
			$(".searchbox").html("");
		  $(' .movie_list .movie_page a').eq(0).addClass('hover');
		
	}
    //ati p89 end
	
	//jei seg ywelai zeu yeud
    key_events.backhome(); //page_load
    $('.hover').removeClass('hover');
    $('.activeview .movie_list a').eq(0).addClass('hover');
	//jei end
    
// render.movie_list_normal({rows:[
// {},{},{},{},{},{},
// {},{},{},{},{},{},
// {},{},{},{},{},{},
// {}]});
	
    //$('body').hide();
}(window));

//qc7  all onver
function all___________________________________________over(){}

//  $(".searchbox").css("left","-250px").css("top","-500px");
window.setTimeout(function(){
	$("#grid_div a").each(function(){
	//	alert($(this).attr("mvid"));
		$(this).attr("mid",$(this).attr("mvid"));
	});
},1000);

function page_load()
{
	//$("#cate_1_up")
	bindEvtQc9("cate_1_up",function(){
		$("#cate2").addClass("hover");
		$("#cate_1").removeClass("hover");
	});
	bindEvtQc9("cate_1_right",function(){
		$("#cate_2").addClass("hover");
		$("#cate_1").removeClass("hover");
	});

	bindEvtQc9("first_movie_up",function(){
		$("#menu1").addClass("hover");
		$("#first_movie").removeClass("hover");
	});

	bindClsEvt("cateitem_enter",function(){
		
		$("#menu2").addClass("enterCateItem");
		
	} );
	
	$(".movie_list a").each(function(){
		
		
	}); 

	/*

	$(".movie_page a").each(){
		//$(this)_up=
		
	}
	*/
	//direction
	
}

function set_next_hover(ori_next_hover,curr_hover_obj,direction){
	if($(curr_hover_obj).attr("id")=="cate_1"&& direction=="up")
	{
		//if(direction=="up")
			var next=$("#cate_2");
		  $(next_hover).addClass('hover');
		return next;
	}
	
	
	
	
}

$( function(){
	page_load();
	
});

